package com.property.manage.filter;

import com.google.gson.Gson;
import com.guardchina.framework.auth.jwt.JsonWebToken;
import com.guardchina.framework.util.constant.Constants;
import com.guardchina.framework.util.constant.HeaderKeyConst;
import com.guardchina.framework.util.constant.ResultStatus;
import com.guardchina.framework.util.exception.login.TokenExpException;
import com.guardchina.framework.util.exception.login.TokenInvalidException;
import com.guardchina.framework.util.exception.login.TokenRefreshException;
import com.guardchina.framework.util.model.ResultHolder;
import com.guardchina.framework.util.utils.DateUtil;
import com.guardchina.framework.web.api.TokenValidator;
import com.guardchina.framework.web.model.RequestWrapper;
import com.guardchina.framework.web.model.TimeFeature;
import com.guardchina.framework.web.model.TokenValidatorHolder;
import com.guardchina.framework.web.model.UserFeature;
import com.guardchina.framework.web.properties.LoginProperties;
import com.property.manage.properties.AuthProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述 系统授权
 *
 * @author lwb
 * @since 2020/3/19
 */
@Slf4j
public class AuthFilter implements Filter {

    private AuthProperties authProperties;

    public AuthFilter(AuthProperties authProperties){
        this.authProperties = authProperties;
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        LocalDate now = LocalDate.now();

        if(now.isAfter(DateUtil.getLocalDate(authProperties.getDate()))){
            ResultHolder resultHolder = ResultHolder.error(ResultStatus.TOKEN_NOT_EXIST_EXCEPTION, authProperties.getMessage());
            response.addHeader(HeaderKeyConst.TOKEN_GET_KEY, "true");
            errorResponse(response, resultHolder);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);

    }

    private void errorResponse(HttpServletResponse response, ResultHolder resultHolder) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(new Gson().toJson(resultHolder));
        response.flushBuffer();
        return;
    }

    @Override
    public void destroy() {

    }


}
